package com.couldsail.takeaway.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class AddressLocationUtil {
    /**
     * Key
     */
    private static final String KEY="0effb4a3b13c27256179de1c8bdee7d9";


    public  static String GD_URL= "https://restapi.amap.com/v3/geocode/geo?address=%s&key=%s";

    public  static String DIS_URL = "https://restapi.amap.com/v3/distance?key=%s&origins=%s,%s&destination=%s,%s";

    /**
     * 成功标识
     */
    private static final String SUCCESS_FLAG="1";

    /**
     * 根据地址获取对应的经纬度信息
     * @param address
     * @return
     */
    public static String getLonAndLatByAddress(String address) {
        String location = "";
        String formattedUrl = String.format(GD_URL, address, KEY);

        // 高德接口返回的是 JSON 格式的字符串
        String queryResult = getResponse(formattedUrl);
        JSONObject obj = JSONObject.parseObject(queryResult);

        // 检查状态码
        if (SUCCESS_FLAG.equals(String.valueOf(obj.get("status")))) {
            // 获取 geocodes 数组
            JSONArray geocodesArray = obj.getJSONArray("geocodes");

            // 检查 geocodes 是否为空
            if (geocodesArray != null && !geocodesArray.isEmpty()) {
                // 获取第一个元素
                JSONObject jobJSON = geocodesArray.getJSONObject(0);
                location = jobJSON.getString("location"); // 获取位置字符串
            } else {
                throw new RuntimeException("未找到与地址匹配的经纬度信息。");
            }
        } else {
            throw new RuntimeException("地址转换经纬度失败，错误码：" + obj.get("infocode"));
        }

        return location;
    }
    /**
     * 计算两个经纬度点之间的直线距离（单位：千米）
     * @param lat1 点1纬度
     * @param lon1 点1经度
     * @param lat2 点2纬度
     * @param lon2 点2经度
     * @return 距离（千米）
     */

    public static double getDistance(String lon1, String lat1, String lon2, String lat2) throws Exception {
        double distance = 0.0;
        String urlString = String.format(DIS_URL, KEY, lon1, lat1, lon2, lat2); // 注意经纬度参数的顺序

        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 解析 JSON 响应
        String jsonResponse = response.toString();
        JSONObject obj = JSONObject.parseObject(jsonResponse);

        // 检查状态码
        if ("1".equals(String.valueOf(obj.get("status")))) {
            // 获取 results 数组
            JSONArray resultsArray = obj.getJSONArray("results");

            // 检查 results 是否为空
            if (resultsArray != null && !resultsArray.isEmpty()) {
                // 获取第一个元素
                JSONObject resultJSON = resultsArray.getJSONObject(0);
                distance = Double.parseDouble(resultJSON.getString("distance")); // 获取距离
            } else {
                throw new RuntimeException("计算距离失败，结果为空");
            }
        } else {
            throw new RuntimeException("计算距离失败，错误码：" + obj.get("infocode"));
        }
        return distance/1000;
    }
    /**
     * 发送请求
     *
     * @param serverUrl 请求地址
     */
    private static String getResponse(String serverUrl) {
        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}